﻿//create angular module
var app = angular.module("app", ["ngRoute"]);

//Sets and Removes Tokens
app.factory("SessionHandler", function ($window) {
    //Puts token in storage
    var setLoggedInToken = function (token) {
        $window.sessionStorage.setItem("token", token);
    };
    //Clear the login token
    var removeLoggedInToken = function () {
        $window.sessionStorage.removeItem("token");
    };
    return {
        setLoggedInToken: setLoggedInToken,
        removeLoggedInToken: removeLoggedInToken
    }
});

app.factory("LoginService", function ($q, $http, SessionHandler) {
    var processLogin = function (username, password) {
        var deferred = $q.defer();
        $http({
            method: "POST",
            data: "username=" + username + "&password=" + password + "&grant_type=password",
            headers: { "Content-Type": "application/x-www-form-urlencoded" },
            url: "/Token",
            isArray: false
        }
        ).success(
            function (data) {
                SessionHandler.setLoggedInToken(data.access_token);
                deferred.resolve();
            }
        ).error(
            function (data, status) {
                SessionHandler.removeLoggedInToken();
                deferred.reject(status);
            }
        );
        return deferred.promise;
    }

    var processLogout = function () {
        var deferred = $q.defer();
        $http({
            method: "POST",
            url: "/api/Account/Logout"
        }
        ).succes(
            function (data, status) {
                SessionHandler.removeLoggedInToken();
                deferred.resolve();
            }
        ).error(
            function (data, status) {
                deferred.reject(status);
            }
        );
        return deferred.promise;
    };

    return {
        processLogin: processLogin,
        processLogout: processLogout
    }
});

//Create Our Interceptor
app.factory("AuthInterceptor", function ($window) {
    return {
        request: function (config) {
            config.headers = config.headers || {};
            if ($window.sessionStorage.getItem("token")) {
                config.headers.Authorization = "Bearer " + $window.sessionStorage.getItem("token");
            }
            return config;
        }
    };

});

//Create our config for routes and install the interceptor
app.config(function ($routeProvider, $httpProvider) {
    $httpProvider.interceptors.push("AuthInterceptor");
    $routeProvider.when("/LogIn",
        {
            templateUrl: "/App/Views/ngHome.html",
            controller: "ngHomeController"
        }
    ).when("/",
        {
            templateUrl: "/App/Views/ngIndex.html",
            controller: "ngIndexController"
        }
    ).when("/ArtDetail/:id",
        {
            templateUrl: "/App/Views/ngArtDetail.html",
            controller: "ngArtDetailController"
        }
    ).when("/NewArt",
        {
            templateUrl: "/App/Views/ngNewArt.html",
            controller: "ngNewArtController"
        }
    ).when("/EditArt/:id",
        {
            templateUrl: "/App/Views/ngEditArt.html",
            controller: "ngEditArtController"
        }
    )
});

//Create Controllers
app.controller("ngHomeController", function ($scope, $window, $q, LoginService) {
    $scope.login = function () {
        LoginService.processLogin($scope.user.username, $scope.user.password
            ).then(
                function () {
                    $scope.token = $window.sessionStorage.getItem("token");
                },
                function (status) {
                    $scope.token = status;
                }
            );
    };
});

app.ArtPiece = function (art) {
    this.Name = art.Name;
    this.Artist = art.Artist;
    this.Image = art.Image;
    this.User = art.User;
    this.ApplicationUserId = art.ApplicationUserId;
};

//create services to process our logins
app.factory("ArtPieceManifest", function () {
    return [];
});


app.controller("ngIndexController", function ($http, $scope, $location, ArtPieceManifest) {
    $scope.ArtList = ArtPieceManifest;

    $http.get("api/Art/").success(function (data) {
        for (var x in data) {
            //console.log(data[x]);
            ArtPieceManifest.push(data[x]);
        }
    }).error(function (data) {
        console.log((data));
    });

    $scope.Login = function () {
        $location.path("LogIn/");
    }

    $scope.ArtDetail = function (id) {
        $location.path("ArtDetail/" + id);
    };

    $scope.AddNewArt = function () {
        $http.get("api/Art/"+1).success(function () {
            //console.log(data);
            $location.path("NewArt/");
        }).error(function (data) {
            alert("Oops! You need to be logged in to do that!")
        });
        
    };

});

app.controller("ngArtDetailController", function ($http, $scope, $location, $routeParams, ArtPieceManifest) {
    $scope.art = "";
    for (var i in ArtPieceManifest) {
        if (ArtPieceManifest[i].Id == $routeParams.id) {
            $scope.art = ArtPieceManifest[i];
            console.log(ArtPieceManifest[i]);
            break;
        }
    };

    $scope.EditArt = function (id) {
        $http.get("api/Art/"+id).success(function (data) {
            alert("you are authorized");
            $location.path("EditArt/" + id);
        }).error(function (data) {
            alert("Oops! You need to be the owner to do that!")
        });
    };

    $scope.DeleteArt = function (id) {
        $http.get("api/Art/"+id).success(function (data) {
            alert("you are authorized");
            $http.delete("api/Art/" + id).success(function ()
            {
                for (var i in ArtPieceManifest) {
                    if (ArtPieceManifest[i].Id == id) {
                        ArtPieceManifest.splice(i, 1);
                        break;
                    }
                };
                $location.path("/")
            }).error(function ()
            {
                alert("Something went wrong with the delete")
            });
        }).error(function (data) {
            alert("Oops! You need to be the owner to do that!")
        });
    };

    $scope.saveChanges = function () {

    };

});

app.controller("ngNewArtController", function ($scope, $http, $location, ArtPieceManifest) {

    $scope.AddNewArt = function (artpiece) {
        console.log(artpiece);
        $http.post("api/Art/", artpiece).success(function (data) {
            artpiece = data;
            artpiece.Id = data.Id;
            artpiece.ApplicationUserId = data.ApplicationUserId;
            ArtPieceManifest.push(artpiece);
            $location.path("ArtDetail/" + artpiece.Id)
        }).error(function () {
            console.log(JSON.stringify(data));
            $location.path("/");
        });
    };

});

app.controller("ngEditArtController", function ($scope, $http, $location, $routeParams, ArtPieceManifest) {
    $scope.art = "";
    for (var i in ArtPieceManifest) {
        if (ArtPieceManifest[i].Id == $routeParams.id) {
            $scope.art = ArtPieceManifest[i];
            break;
        }
    };

    $scope.SaveChanges = function (artpiece) {
        for (var i in ArtPieceManifest) {
            if (ArtPieceManifest[i].Id == $routeParams.id) {
                artpiece.ApplicationUserId = ArtPieceManifest[i].ApplicationUserId;
                artpiece.Id = ArtPieceManifest[i].Id;
                break;
            }
        }
        console.log(artpiece);
        $http.put("api/Art/", artpiece).success(function (data) {
            artpiece = data;
            //artpiece.Id = data.Id;
            console.log(artpiece);
            console.log(data);
            for (var i in ArtPieceManifest) {
                if (ArtPieceManifest[i].Id == artpiece.Id) {
                    ArtPieceManifest[i].Name = artpiece.Name;
                    ArtPieceManifest[i].Artist = artpiece.Artist;
                    ArtPieceManifest[i].Image = artpiece.Image;
                    break;
                }
            };
            $location.path("ArtDetail/" + artpiece.Id);
        }).error(function () {
            console.log(JSON.stringify(data));
            $location.path("/");
        });
    }

});